// pages/lists/lists.js
const app = getApp()
Page({
  data: {
    lists: []
  },
  onShow(options) {
    this.getTaskLists()
  },
  getTaskLists: function() {
    console.log(wx.getStorageSync('openid'))
    wx.showLoading({
      title: '加载中',
    })
    var that = this
    wx.request({
      url: app.apiHost + 'task/lists',
      data: {
        openid: wx.getStorageSync('openid')
      },
      method: 'GET',
      success: function(res) {
        wx.hideLoading()
        var result = res.data
        console.log(result)
        if(result.status == 200) {
          that.setData({
            lists: result.data
          })
        } else if (result.status == 403){
          wx.navigateTo({
            url: '../login/login',
          })
        } else {
          wx.showToast({
            title: result.message,
            icon: 'none'
          })
        }
      }
    })
  },
  modify: function(option) {
    var index = option.currentTarget.dataset.index
    console.log(index)
    var task_id = option.currentTarget.dataset.id
    var temp = this.data.lists
    if(temp[index].status == 1) {
      temp[index].status = 2
      temp[index].status_title = '已完成'
    } else {
      temp[index].status = 1
      temp[index].status_title = '未完成'
    }
    this.setData({
      lists: temp
    })
    wx.request({
      url: app.apiHost + 'task/modify',
      data: {
        openid: wx.getStorageSync('openid'),
        task_id: task_id
      },
      method: 'POST',
      success: function(res) {
        var result = res.data
        if(result.status == 200) {
          console.log(result)
        } else {
          wx.showToast({
            title: result.message,
            icon: 'none'
          })
        }
      }
    })
  },
  onPullDownRefresh: function() {
    this.getTaskLists()
  },
  delete: function(option) {
    var index = option.currentTarget.dataset.index
    var task_id = option.currentTarget.dataset.id
    var temp = this.data.lists
    temp.splice(index, 1)
    this.setData({
      lists: temp
    })
    wx.request({
      url: app.apiHost + 'task/delete',
      data: {
        openid: wx.getStorageSync('openid'),
        task_id: task_id
      },
      method: 'POST',
      success: function(res) {
        var result = res.data
        if(result.status == 200) {

        } else {

        }
      }
    })
  },
  jumpToAdd: function() {
    wx.navigateTo({
      url: '../add/add',
    })
  }
})